import request from '@/utils/request'
import { getStaticUserInfo } from '@/utils/user'
import { getDetail as getRole } from '@/api/role'
import { asyncRoutes } from '@/router'

export async function login(data) {
  const { type = '' } = data
  return request({
    url: `/activitylogin`,
    method: 'post',
    data,
  })
}

export async function socialLogin(data) {
  return request({
    url: '/socialLogin',
    method: 'post',
    data,
  })
}

export async function getUserRoles(data) {
  // return new Promise((resolve) => {
  //   resolve([
  //     {
  //       id: '1',
  //       name: '首页',
  //       default: '1',
  //     },
  //     {
  //       id: '2',
  //       name: '活动管理',
  //       default: '1',
  //       next: [
  //         {
  //           id: '1',
  //           name: '活动列表',
  //           default: '1',
  //         },
  //       ],
  //     },
  //   ])
  // })
  return request({
    url: '/getmenu',
    method: 'post',
    data,
  })
}

// TODO 换真实接口请求
export async function getUserInfo() {
  const staticUserInfo = getStaticUserInfo()
  const { type, role_id } = staticUserInfo
  //const ro = getUserRoles({ role_id: staticUserInfo.role_id })
  // roles 角色数组, 格式: ['父角色', '子角色'], 如: ['property'] 或 ['activity', 'xx']
  // 注: userInfo 接口需要直接返回该字段
  const arr = await getUserRoles({
    role_id: role_id,
  })
  let routes = JSON.parse(JSON.stringify(asyncRoutes))
  let permission = []
  for (let item of routes[0].children) {
    if (item.key && arr.role_id.includes(item.key)) {
      permission = permission.concat(item.meta.roles)
    }
    if (item.children) {
      for (let it of item.children) {
        if (it.key && arr.role_id.includes(it.key)) {
          permission = permission.concat(it.meta.roles)
        }
      }
    }
  }
  const roles = [type, ...permission]
  return {
    code: 1,
    data: { ...staticUserInfo, roles },
  }
}

export function logout() {
  const staticUserInfo = getStaticUserInfo()
  const { type } = staticUserInfo
  return request({
    url: `/activitylogout`,
    method: 'post',
  })
}
